<?php

namespace common\jobs;

use Yii;
use yii\base\Exception;
use common\models\inventory\InventoryLog;
use common\models\rfid\Rfid;

/**
 * 评论之后执行队列任务
 * Class AfterCommentJob.
 */
class InventoryBatchJob extends \yii\base\BaseObject implements \yii\queue\RetryableJobInterface {

    public $batch_id = 0;

    /**
     * @param \yii\queue\beanstalk\Queue $queue which pushed and is handling the job
     */
    public function execute($queue) {
        echo 'Ready...';
        if (!$this->batch_id) {
            echo 'No batch id.';
            throw new Exception('No batch id.');
        }
        echo 'Run queue id:' . $queue->workerPid;
        $query = InventoryLog::find()->where([
            'batch_id' => $this->batch_id,
            'status' => InventoryLog::STATUS_DEFAULT
        ]);
        foreach ($query->each() as $log) {
            $rfid = Rfid::findBySn($log->sn);
            if ($rfid) {
                $log->rf_id = $rfid->id;
                $log->bill_id = $rfid->bill_id;
                $log->status = InventoryLog::STATUS_COMPLETED;
            } else {
                $log->status = InventoryLog::STATUS_UNDEFIND;
            }
            if (!$log->save()) {
                Yii::error($log->errors);
                throw new Exception(print_r($log->errors, true));
            }
        }
        echo 'completed.';
    }

    /**
     * @inheritdoc
     */
    public function getTtr() {
        echo 'ttr';
        return 2;
    }

    /**
     * @inheritdoc
     */
    public function canRetry($attempt, $error) {
        echo 'can try';
        return $attempt < 5 && $error;
    }

}
